#include "public.h"
#include "esp8266.h"
#include "ringbuffer.h"


#if (TTY_RXBUF_SIZE & (TTY_RXBUF_SIZE - 1)) != 0
    #error "TTY_RXBUF_SIZE must be power of 2 !"
#endif

#if (TTY_TXBUF_SIZE & (TTY_TXBUF_SIZE - 1)) != 0
    #error "TTY_TXBUF_SIZE must be power of 2 !"
#endif


static unsigned char rxbuf[];


void esp8266_uart_init(int bound)
{

	RCC_APB1PeriphClockCmd(ESP8266_USART_CLK, ENABLE);		/* 使能USART3时钟 */
	RCC_APB2PeriphClockCmd(ESP8266_USART_GPIO_CLK, ENABLE); /* 使能GPIOB时钟 */

	gpio_conf(ESP8266_USART_TX_PORT, ESP8266_USART_TX_PIN, GPIO_Mode_AF_PP, GPIO_Speed_50MHz);		 /* USART3_TX GPIOB.10 */
	gpio_conf(ESP8266_USART_RX_PORT, ESP8266_USART_RX_PIN, GPIO_Mode_IN_FLOATING, GPIO_Speed_50MHz); /* USART3_RX GPIOB.11初始化 */

	nvic_conf(ESP8266_USART_IRQ, 0, 0, ENABLE);											  /* Usart3 NVIC 配置 */
	uart_conf(ESP8266_USARTx, bound, USART_WordLength_8b, USART_StopBits_1, USART_Parity_No); /* USART 初始化设置 */
}

void ESP8266_init()
{
	RCC_APB2PeriphClockCmd(ESP8266_CH_PD_CLK | ESP8266_RST_CLK, ENABLE);

	gpio_conf(ESP8266_CH_PD_PORT, ESP8266_CH_PD_PIN, GPIO_Mode_Out_PP, GPIO_Speed_50MHz); /* 配置CHIP_EN引脚 */
	gpio_conf(ESP8266_RST_PORT, ESP8266_RST_PIN, GPIO_Mode_Out_PP, GPIO_Speed_50MHz); /* 配置RST引脚 */

	esp8266_uart_init(115200);
}



void USART3_IRQHandler(void)
{
	uint8_t ch = 0;

	if(USART_GetITStatus(ESP8266_USARTx, USART_IT_RXNE) != RESET) {
		ch = USART_ReceiveData(ESP8266_USARTx);

		if(strESP8266_Fram_Record.InfBit.FramLength < (RX_BUF_MAX_LEN - 1)) {
			strESP8266_Fram_Record.Data_RX_BUF[strESP8266_Fram_Record.InfBit.FramLength++] = ch;
		}
	}

	if(USART_GetITStatus(ESP8266_USARTx, USART_IT_IDLE) == SET) {
		strESP8266_Fram_Record.InfBit.FramFinishFlag = 1;
		ch = USART_ReceiveData(ESP8266_USARTx);

		ucTcpClosedFlag = strstr(strESP8266_Fram_Record.Data_RX_BUF, "CLOSED\r\n")? 1:0;
	}
}

bool ESP8266_Cmd(char *cmd, char *reply1, char *reply2, u32 waittime)
{
	strESP8266_Fram_Record.InfBit.FramLength = 0;
	
}





